package com.wan.service.impl;

import cn.hutool.crypto.SecureUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wan.entity.LoginUser;
import com.wan.entity.User;
import com.wan.mapper.UserMapper;
import com.wan.service.IPermissionService;
import com.wan.service.IUserService;
import com.wan.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
	@Autowired
	private IPermissionService permissionService;

	@Override
	public LoginUser findUser(UserVo vo) {
		// 生成 token 并设置到 loginUser 对象中
		LoginUser loginUser = new LoginUser();
		String token = UUID.randomUUID().toString();
		loginUser.setToken(token);
		// 根据用户名查询用户
		User user = this.getOne(new QueryWrapper<User>().eq("username", vo.getUsername()));
		// 用户不存在，直接返回 null
		if (user == null) {
			return null;
		}
		// 查询用户的权限列表并设置到登录用户对象
		List<String> permissions = permissionService.selectPermissionValueByUserId(user.getId());
		loginUser.setPermissions(permissions);
		// 对传入的密码进行加密
		String encryptedPwd = SecureUtil.md5(vo.getPassword());
		// 比较加密后的密码是否与数据库中的一致
		if (!encryptedPwd.equals(user.getPassword())) {
			return null;
		}
		// 密码验证通过，设置用户信息到登录对象
		loginUser.setUser(user);
		return loginUser;
	}
}
